package cn.ibizlab.util.common;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import org.springframework.util.ObjectUtils;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class JsonFieldExtractor {

    public static JSONObject extractMap(Map params, Map<String, Object> fieldMappings) {
        if (params == null || params.isEmpty() || fieldMappings == null) {
            return new JSONObject();
        }
        return extractJSON(new JSONObject(params), fieldMappings);
    }
    /**
     * 从JSON字符串中提取指定字段到Map
     * @param jsonObject
     * @param fieldMappings 字段映射规则（目标字段名 -> JSON路径表达式）
     * @return 包含提取结果的Map（字段名 -> 提取值）
     */
    public static JSONObject extractJSON(JSONObject jsonObject, Map<String, Object> fieldMappings) {

        if (jsonObject == null || jsonObject.isEmpty() || fieldMappings == null) {
            return new JSONObject(jsonObject);
        }
        JSONObject result = new JSONObject(jsonObject);
        try {


            fieldMappings.forEach((fieldName, pathExpression) -> {
                if(!ObjectUtils.isEmpty(pathExpression)) {
                    String[] parts = parsePathWithDefault((String)pathExpression);
                    String path = parts[0];
                    String defaultValue = parts[1];

                    Object value = JSONPath.eval(jsonObject, normalizeJsonPath(path));

                    result.put(fieldName, value==null?defaultValue:value);
                }

            });

            return result;
        } catch (Exception e) {
            return result;
        }
    }

    public static String extractJSON(JSONObject jsonObject, String pathExpression) {
        String strValue = "";
        if (jsonObject == null || jsonObject.isEmpty() || ObjectUtils.isEmpty(pathExpression)) {
            return strValue;
        }


        try {
            String[] parts = parsePathWithDefault(pathExpression);
            String path = parts[0];
            String defaultValue = parts[1]==null ? "":parts[1];


            strValue = convertToString(JSONPath.eval(jsonObject, normalizeJsonPath(path)), defaultValue);


        } catch (Exception e) {

        }
        return strValue;
    }

    /**
     * 解析带默认值的路径表达式（格式：path|default）
     */
    private static String[] parsePathWithDefault(String expression) {
        String[] parts = expression.split("\\|", 2);
        String path = parts[0].trim();
        String defaultValue = (parts.length > 1) ? parts[1].trim() : null;
        return new String[]{path, defaultValue};
    }

    /**
     * 转换为标准JSONPath格式（自动添加根节点标识符）
     */
    private static String normalizeJsonPath(String path) {
        if (path.startsWith("$.") || path.startsWith("$[")) {
            return path;
        }
        return "$." + path;
    }

    /**
     * 安全转换对象为字符串
     */
    private static String convertToString(Object value, String defaultValue) {
        if (value == null) {
            return defaultValue;
        }

        if (value instanceof String) {
            return (String) value;
        }

        if (value instanceof Number || value instanceof Boolean) {
            return value.toString();
        }

        // 处理嵌套对象
        return JSONObject.toJSONString(value);
    }
}